<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="headerShow">
                <!-- <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="工序名称">
                            <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                                v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                                @focus="focusSel">
                                <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                            </a-select>
                        </a-form-item>
                    </a-form> -->
            </div>
            <!-- <div class="my-divisders">
                    <a-divider orientation="center">
                        <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                        <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                    </a-divider>
                </div> -->
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exports" @import="importHandler" @edit="edit" @excel="downloadHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
                    :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                    :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"
                    :localeText="localeText1" @columnResized="onColumnResized" @columnMoved="onColumnMoved"></AgGridVuesCopys>
            </a-spin>
        </template>
        <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize" :current="pagination.page"
            :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
            style="justify-content: center" />

        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm8">
                    <a-form-item label-col-flex="80px" label="是否进缸">
                        <a-input class="bacClass" v-model="huixiuyuanyin" allow-clear />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="备注">
                        <a-textarea class="bacClass" v-model="beizhu" :max-length="400" allow-clear show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
        <a-modal :visible="visible" @ok="handleOk" @cancel="handleCancel" okText="打印" cancelText="关闭" unmountOnClose>
            <template #title>
                打印二维码
            </template>
            <div id="feeding">
                <QrcodeVue :value="qrData.code"></QrcodeVue>
                <div style="display:inline-block;vertical-align:top;margin-left:15px;width: 150px;line-height:2.5em;">
                    <span>工段: {{ decodeURI(qrData.sectionName) }}</span>
                    <br />
                    <span>工序名称: {{ decodeURI(qrData.processName) }}</span>
                    <br />
                </div>
            </div>
        </a-modal>
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { pagingList } from "@/api/paging";
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import { AnyARecord } from 'dns';

import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'
import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
interface BrandInfo {
    "id": any,
    "remark": string | undefined,
    "createName": string | undefined,
    "createTime": string | undefined,
    "updateName": string | undefined,
    "updateTime": string | undefined,
    "deleteState": any,
    "obsoleteState": any,
    "serial": any,
    "sectionCode": string | undefined,
    "sectionName": string | undefined,
    "processName": string | undefined,
    "sectionNames": any
}

export default {
    name: "FeedingOrNot",
    setup() {
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            pagination.page = val
            doRefresh();
        }

        function change1(val: any) {
            pagination.pageSize = val
            doRefresh();
        }
        const headerShow = ref<boolean>(true)
        //查询方法
        function doRefresh() {
            pageData.pageLoading = true
            // updateGridState01()
            post({
                url: "/dwWorkShop/whetherCylinder/findWhetherCylinder?page=" + pagination.page + "&limit=" + pagination.pageSize,
                data: {
                    "repairNature": ""
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        // pagination.setTotalSize(data.total);
                        // sessionStorage.setItem("染缸aa",JSON.stringify(data.data))
                        gridOption.value.setRowData(data.data.list);
                        total.value = data.data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "序号",
                key: "id",
                dataIndex: "id",
                width: 150,
            },
            {
                title: "是否进缸",
                key: "whetherCylinder",
                dataIndex: "whetherCylinder",
                width: 150
            },

            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 200
            },
            {
                title: "最初建立人",
                key: "updateBy",
                dataIndex: "updateBy",
                width: 150
            },
            {
                title: "建立时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 200
            },
            {
                title: "操作",
                key: "act",
                dataIndex: "act",
                width: 80,
                fixed: 'right'
            },

        ]);
        let tc: any[] = tableColumns.map((o) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            obj['width'] = 300
            if (o.dataIndex === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj['width'] = 100
                obj['cellRenderer'] = {
                    template: `<a-space>
                                   <el-button style="color:#165dff;" link @click="a1">修改</el-button>
                               </a-space>`,
                    setup(props: any) {
                        const a1 = () => {
                            editHandler(props.params.data)
                        }
                        const a2 = () => {
                            GenerateBtn(props.params.data)
                        }
                        return {
                            a1,
                            a2
                        }
                    }

                }
            }

            return obj
        })



        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            nameList: [],
            pageLoading: boolean,
            typeList: [],
            dropDownData1: any,
            rHeight: any,
            btnList: any[],
            isEdit: boolean,
            sectionNames: [],

        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增工序',
            dropDownData: "",
            pageLoading: false,
            typeList: [],
            dropDownData1: "",
            rHeight: 0,
            btnList: [],
            isEdit: false,
            sectionNames: []
        });

        interface gcType {
            id: any,
            company: any,
        }
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ "processName": "" });
        }

        //下拉数据
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { processName: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "/pdm/worksectionWorkprocedure/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["processName"])
                    });
                    pageData.nameList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        const focusSel2 = () => {
            selCxAll2({ firm: "", page: 1, size: 10 });
        }
        const options2 = ref<any>(pageData.sectionNames);
        const loadings2 = ref(false);
        const handleSearch2 = (value: any) => {
            if (value) {
                const ob = { boxName: value, deleteState: 0 }
                loadings2.value = true;
                selCxAll2(ob);
                options2.value = pageData.sectionNames;
                loadings2.value = false;
            } else {
                options2.value = []
            }
        };
        function selCxAll2(val: any) {
            post({
                url: "/aps/dwMachine/getMachinePage",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    //sessionStorage.setItem("设备编号",JSON.stringify(data.list))
                    data.list.forEach((o: any, index: any) => {
                        dataForm8.shebeibianhaolist[index] = o.machineCode
                    })
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        onMounted(() => {
            doRefresh();
            // 切换tap到本页面执行的方法
            emitter.on("OperationDefinition", () => {
                // selCxAll({});
                doRefresh();
            });
        });

        let cxbl = {}
        //查询
        const selectHandler = () => {
            pagination.page = 1
            cxbl = pageData.dropDownData
            doRefresh();
        }
        const queryData = reactive({
            processName: ""
        });
        const addHandler = () => {
            biaoji.value = "增加"
            // selCxAll1({ processName: "" })
            huixiuyuanyin.value = ""
            beizhu.value = ""
            pageData.showAdd = true
            pageData.sideTitle = '是否进缸'
        }
        const dataForm = reactive<BrandInfo>({
            "id": null,
            "remark": "",
            "createName": "",
            "createTime": "",
            "updateName": "",
            "updateTime": "",
            "deleteState": 0,
            "obsoleteState": "",
            "serial": 0,
            "sectionCode": "",
            "sectionName": "",
            "processName": "",
            "sectionNames": "",


        })
        const dataForm8 = ({
            number: "",
            capacity: 0,
            tubeNum: 0,
            price: 0,
            priceUnit: 0,
            remark: "",
            shebeibianhaolist: [] as any
        })
        // 表格准备事件
        const gridOption = ref()
        const colState = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
            colState.value = params.columnApi
        }

        const formRef = ref<FormInstance>()
        const sideOk = () => {
            // sessionStorage.setItem("备注哦",beizhu.value)
            pageData.pageLoading = true;
            if (biaoji.value == "增加") {
                post({
                    url: '/dwWorkShop/whetherCylinder/saveWhetherCylinder',
                    data: [{

                        "whetherCylinder": huixiuyuanyin.value,
                        "remark": beizhu.value
                    }]
                }).then(({ code, data, message }: any) => {
                    if (code === 200) {
                        Message.success({
                            content: '添加成功',
                            duration: 5000
                        })
                        pageData.pageLoading = false;
                        pageData.showAdd = false;
                        pagination.page = 1
                        doRefresh()
                    } else {
                        Message.error({
                            content: message,
                            duration: 5000
                        })
                    }
                }).finally(() => {
                    pageData.pageLoading = false
                });
            } else {
                post({
                    url: '/dwWorkShop/whetherCylinder/updateWhetherCylinder',
                    data: [{
                        "id": id.value,
                        "whetherCylinder": huixiuyuanyin.value,
                        "remark": beizhu.value
                    }]
                }).then(({ code, data, message }: any) => {
                    if (code === 200) {
                        Message.success({
                            content: '修改成功',
                            duration: 5000
                        })
                        pageData.pageLoading = false;
                        pageData.showAdd = false;
                        pagination.page = 1
                        doRefresh()
                    } else {
                        Message.error({
                            content: message,
                            duration: 5000
                        })
                    }
                }).finally(() => {
                    pageData.pageLoading = false
                });
            }
        }
        const deleteHandler = () => {
            var shuzu = [] as any

            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }
            gridOption.value.getSelectedRows().map((o: any) => {
                shuzu.push({ id: o.id })
            })
            sessionStorage.setItem("删除", JSON.stringify(shuzu))
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: '/dwWorkShop/whetherCylinder/deleteWhetherCylinder',
                        data: shuzu
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: '修改失败',
                                duration: 5000
                            })
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }
        const editHandler = (record: any) => {

            biaoji.value = "修改"

            id.value = record.id
            beizhu.value = record.remark
            huixiuyuanyin.value = record.whetherCylinder
            pageData.showAdd = true


        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })
        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            // dataForm.sectionCode = dataForm.sectionCode.toUpperCase();
        }
        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows() === 0) {
                Message.error('请先勾选');
                return
            } else {
                //将表头拼接出来
                let head = "<th>编号</th><th>品牌名称</th><th>布类类型</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["brandCode"] + "</td>";
                    body += "<td>" + o["brandName"] + "</td>";
                    body += "<td>" + o["clothClass"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '品牌资料', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            axios.get(baseURL + '/product/Brand/uploadModel', {
                responseType: 'blob',
                headers: {
                    token: sessionStorage.getItem('USER-TOKEN-KEY')
                }
            }).then((res) => {
                if (res.status === 200) {
                    filedownload(res.data, '品牌资料.xlsx')
                }
            })
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/Brand/importModelData', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        //下拉数据
        const options1 = ref<any>(pageData.nameList);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = {
                    key: value,
                    deleteState: 0
                }
                loading.value = true;
                selCxAll1(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询 
        function selCxAll1(val: any) {
            post({
                url: "/pdm/workprocedure/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.nameList = data;
                } else {
                    // Message.error({
                    //     content: "查询失败！",
                    //     duration: 5000,
                    // });
                }
            });
        }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({ "key": "" });
        }
        // //设置权限
        // // ['查询', '新增', '删除', '导出', '导入']
        // const permissionStore = usePermission()

        // if (permissionStore.hasPermisson('ppzl.cx')) {

        //     pageData.btnList.push("查询")
        // }
        // if (permissionStore.hasPermisson('ppzl.xz')) {
        //     pageData.btnList.push("新增")
        // }
        // if (permissionStore.hasPermisson('ppzl.sc')) {
        //     pageData.btnList.push("删除")
        // }
        // if (permissionStore.hasPermisson('ppzl.dc')) {
        //     pageData.btnList.push("导出")
        // }
        // if (permissionStore.hasPermisson('ppzl.dr')) {
        //     pageData.btnList.push("导入")
        // }
        // if (permissionStore.hasPermisson('ppzl.xg')) {
        //     pageData.isEdit = true
        // }
        // console.log(permissionStore.hasPermisson('ppzl.cx'));
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            width: 160
        }
        //生成条码
        let qrData: any = reactive({
            sectionName: "",
            processName: "",
        })
        const visible = ref(false);

        const handleOk = () => {
            printJS({
                printable: 'feeding',
                type: 'html',
                targetStyles: ['*'],
            })
            visible.value = false;
        };
        const handleCancel = () => {
            visible.value = false;
        }
        const GenerateBtn = (record: any) => {
            visible.value = true;
            qrData.sectionName = record.sectionName;
            qrData.processName = record.processName;
            qrData.code = JSON.stringify({
                sectionName: encodeURI(record.sectionName),
                processName: encodeURI(record.processName),
            })

        }
        const edit = () => {

        }

        const biaoji = ref("");
        const beizhu = ref("")
        const huixiuyuanyin = ref("")
        const id = ref(null)
        const localeText1: any = ref(localeText)
        const pagingList1: any = ref(pagingList)
        const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('FeedingOrNot01', gridOption, colState, tc)
        const onColumnMoved = () => {
            saveGridState01()
        }
        const onColumnResized = () => {
            saveGridState01()
        }
        return {
            saveOrUpdateGridState01,
            saveGridState01,
            updateGridState01,
            onColumnMoved,
            onColumnResized,
            colState,
            pagingList1,
            localeText1,
            GenerateBtn,
            qrData,
            visible,
            handleOk,
            handleCancel,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            inputBlur,
            exports,
            options,
            loading,
            handleSearch,
            focusSel,
            focusSel2,
            downloadHandler,
            importHandler,
            options1,
            loading1,
            options2,
            loadings2,
            handleSearch1,
            handleSearch2,
            focusSel1,
            headerShow,
            handleChange,
            PageSize,
            change1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            page,
            size,
            edit,
            dataForm8,
            beizhu,
            biaoji,
            huixiuyuanyin,
            id
        };
    },
    components: { Toolbar, PageTabelLayout, QrcodeVue }
}
</script>
<style scoped>
:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}
</style>